import sqlite3
import hashlib
import datetime
import sqlite3

# 直接连接到SQLite数据库
conn = sqlite3.connect('app.db')
cursor = conn.cursor()

# 检查是否已经存在管理员账户
cursor.execute("SELECT id, phone FROM user WHERE is_admin = 1;")
admin_user = cursor.fetchone()

if admin_user:
    print(f'管理员账户已存在: {admin_user[1]}')
else:
    # 管理员账户信息
    phone = '888888'  # 默认管理员手机号
    password = 'admin123'  # 默认管理员密码
    hashed_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
    nickname = '超级管理员'
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # 检查手机号是否已存在
    cursor.execute("SELECT id FROM user WHERE phone = ?;", (phone,))
    existing_user = cursor.fetchone()
    
    if existing_user:
        # 如果手机号已存在，更新该用户为超级管理员
        user_id = existing_user[0]
        cursor.execute(
            "UPDATE user SET password = ?, is_admin = 1, admin_level = 2, nickname = ?, updated_at = ? WHERE id = ?;",
            (hashed_password, nickname, now, user_id)
        )
        conn.commit()
        print(f'已将现有用户(手机号: {phone})更新为管理员')
        print(f'密码: {password}')
        print('请在首次登录后修改密码')
    else:
        # 如果手机号不存在，创建新的管理员账户
        try:
            cursor.execute(
                "INSERT INTO user (phone, password, is_admin, admin_level, nickname, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?);",
                (phone, hashed_password, 1, 2, nickname, now, now)
            )
            conn.commit()
            print(f'管理员账户创建成功:')
            print(f'手机号: {phone}')
            print(f'密码: {password}')
            print('请在首次登录后修改密码')
        except sqlite3.Error as e:
            print(f'创建管理员账户时出错: {e}')

# 关闭连接
cursor.close()
conn.close()

print('初始化完成')